<template>
  <div class="page-container page-footer-btn">
      <van-row>
        <van-col span="24">
          <FortenScan
            ref="scan"
            propPlaceholder="请扫描SN标签"
            propErrorMsg="请扫描正确的SN标签"
            :propTypeArr="['sn','rfid']"
            @scanCall="handleScanOver"
          />
        </van-col>
      </van-row>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="库存信息" name="1">
          <van-form  class="cell-small-box" >
            <van-row>
              <van-col span="12">
                <van-field label="耗材"  border v-model="form.matrName" readonly />
              </van-col>
              <van-col span="12">
                <van-field label="SN"   border v-model="form.sn"  readonly/>
              </van-col>
            </van-row>
            <van-row>
              <van-col span="24">
                <van-field label="货位"   border v-model="form.locationName"  readonly/>
              </van-col>
            </van-row>
            <van-row>
              <van-col span="12">
                <van-field label="品规"  border v-model="form.spec" readonly/>
              </van-col>
              <van-col span="12">
                <van-field label="批次"  border v-model="form.lot" readonly/>
              </van-col>
            </van-row>
            <van-row>
              <van-col span="12" >
                <van-field label="生产日期"   border v-model="form.mfgDate" label-width="70" readonly/>
              </van-col>
              <van-col span="12">
                <van-field label="有效期"   border v-model="form.expDate" label-width="70" readonly/>
              </van-col>
            </van-row>
            <van-row>
              <van-col span="12">
                <van-field label="当前包装单位"  border v-model="form.packageUnit" label-width="100" readonly/>
              </van-col>
              <van-col span="12">
                <van-field label="当前内含数"   border v-model="form.skuQty"  label-width="100"  readonly/>
              </van-col>
            </van-row>
            <van-row>
              <van-col span="12">
                <van-field label="新包装"  border v-model="form.packageProcess"  label-width="60" readonly>
                  <template #button>
                    <van-button plain type="primary" size="mini" @click="selectVisible = true" v-show="form.submitStatus == 0">选择</van-button>
                  </template>
                </van-field>

              </van-col>
              <van-col span="12">
                <van-field label="新包装内含数"   border v-model="form.processRate"  label-width="100"  readonly/>
              </van-col>
            </van-row>
          </van-form>
        </van-collapse-item>
      </van-collapse>
    <van-collapse v-model="activeNames">
      <van-collapse-item  name="2">
        <template #title>
          <div>合并信息 <span  style=" color: #07c160" v-show="form.snNew && form.snNew.length > 4">合并后SN:{{form.snNew}}</span></div>
        </template>

        <van-row  v-if="stockProcessItem.length > 0" class="row-border cell-small-box" >
          <van-col span="4" >
            <van-field label="#"   border  readonly/>
          </van-col>
          <van-col span="4" >
             <van-field label="选择"   border  readonly/>
          </van-col>
       <!--   <van-col span="2" >
            <van-field label="单位"   border   readonly/>
          </van-col>
          <van-col span="2">
            <van-field label="数量"   border    readonly/>
          </van-col>-->
          <van-col span="16">
            <van-field label="SN"   border  readonly/>
          </van-col>
        </van-row>
        <van-checkbox-group v-model="checkIds">

            <van-row  v-for="(item,index)  in stockProcessItem" :key="item.id" class="row-border cell-small-box">
              <van-col span="4" >
                <van-field   border  :value="index + 1" readonly/>
              </van-col>
              <van-col span="4" style="    height: 36px; padding-top: 7px; padding-left: 15px;">
                <van-checkbox :name="item.id" ></van-checkbox>
              </van-col>
              <van-col span="16">
                <van-field   border v-model="item.sn" label-width="0"  readonly/>
              </van-col>
            </van-row>
        </van-checkbox-group>
      </van-collapse-item>
    </van-collapse>

    <van-row type="flex" justify="space-around" class="footer-btn">
      <van-col span="5">
        <van-button type="primary" block @click="handleSubmit(1)" :disabled="form.submitStatus != 0" >
          提交
        </van-button>
      </van-col>
      <van-col span="5">
        <van-button type="info" block @click="utilPrint.print('snprocessmerge',form.id, [form.snNew] )" :disabled="form.submitStatus != 1">
          打印标签
        </van-button>
      </van-col>
      <van-col span="5">
        <van-button type="danger" block @click="handleUnSubmit(3)" :disabled="form.submitStatus != 1">
          取消合并
        </van-button>
      </van-col>
    </van-row>


   <!-- 包装选择-->
    <van-popup position="bottom" closeable v-model="selectVisible" >
      <van-radio-group  @change="selectChange" v-model="selectUnitId" style="margin-top: 40px;">
        <van-cell-group>
          <van-cell  @click="selectChange(item)" v-for="item in matrUnits" :key="item.id" :title="item.unit" clickable  :label="'比率:'+item.rate"  >
            <template #right-icon>
              <van-radio :name="item.id" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
  </div>
</template>
<script>
import { Card } from 'vant'
import barcodeParse from '@/util/barcodeParse.js'

export default {
  data() {
    return {
      scan: '',
      form: {},
      matrUnits: [],
      selectVisible: false,
      //所选择的新包装
      packageUnitNew: {},
      stockProcessItem: [],
      activeNames: ['1', '2'],
      processType: 2,
      checkIds: [],

      selectUnitId: null
    }
  },
  props: {
    propFlowKey: String
  },
  components: {
    Card
  },
  methods: {
    //扫描
    handleScanOver(scanValue) {
      let params = {
        isScan: 1,
        sn: scanValue,
        processType: this.processType
      }
      this.$ajax.get('/wm/stock_process/barCodeScan', {params}).then(resp => {
        if (resp.code == 0) {
          this.form = resp.data
          this.getMatrUnits()
        }
      })
    },

    //获取包装单位
    getMatrUnits() {
      this.$ajax.get('/base/matrUnit/getByMatr', {params: {matrId: this.form.matrId}}).then(resp => {
        this.matrUnits = resp.data

        //排除当前包装单位,以及单品单位,比率大于当前内含数，并且当前内含数/包装比率为整数
        this.matrUnits =  this.matrUnits.filter(unit => unit.unit != this.form.packageUnit && unit.flagBase != 1 && unit.rate > this.form.skuQty &&  unit.rate % this.form.skuQty == 0)
        if (!this.matrUnits || this.matrUnits.length < 1) {
          this.$notify.warning('当前耗材没有可合并包装单位')
        } else {
          this.selectChange(this.matrUnits[0])
        }
      })
    },

    //包装单位选择后
    selectChange(selectUnit) {
      this.selectVisible = false
      let unit = this.matrUnits.find(item => item.id == selectUnit.id)
      this.form.packageProcess = unit.unit
      this.form.processRate = unit.rate
      this.form.processQty = this.form.skuQty / this.form.processRate
      this.getStockProcessItem()
    },

    //按钮操作
    btnHandle() {
      this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'app_center_package2' })
    },

    //查询可合并的库存明细
    getStockProcessItem() {
      let wrapper = this.$newWrapper().eq('matrId', this.form.matrId ? this.form.matrId : -1)
      wrapper.eq('warehouseId', this.form.warehouseId)
        .eq('packageUnit', this.form.packageUnit)
        .gt('skuQty', 0)
        .eq('lot', this.form.lot)
        .eq('expDate', this.form.expDate)
      wrapper.orderConditions.push({ field: 'inTime', rule: 'desc' })
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
        orderString: JSON.stringify(wrapper.orderConditions)
      }
      this.$ajax.get('/wm/stock//list', {params}).then(resp => {
        this.stockProcessItem = resp.data

        let getOne = this.stockProcessItem.find(ob => ob.sn == this.scan)
        this.checkIds = [getOne.id]

        let needCheckNum = this.form.processRate / this.form.skuQty -  1
        this.stockProcessItem.filter(ob => ob.sn != this.scan).forEach(item => {
          if (needCheckNum != 0) {
            this.checkIds.push(item.id)
            // eslint-disable-next-line no-plusplus
            needCheckNum--
          }
        })
      })
    },
    //提交
    handleSubmit() {
      this.form.processType = this.processType
      if (!this.checkIds || this.checkIds.length < 1) {
        this.$notify.warning('请先选择需要合并的库存记录')
        return
      }
      let checkIdsStr = this.checkIds.join(',')
      let checkedRecords = this.stockProcessItem.filter(ob => checkIdsStr.indexOf(ob.id) != -1)
      if (this.form.skuQty * checkedRecords.length != this.form.processRate) {
        // eslint-disable-next-line no-template-curly-in-string
        let packageNum = this.form.processRate / this.form.skuQty
        this.$notify.warning(`1${this.form.packageProcess}有${packageNum}${this.form.packageUnit}，您目前选择了${checkedRecords.length}${this.form.packageUnit}!`)
        return
      }
      this.utils.loadShow()
      this.form.processQty = 1
      this.form.amount = this.form.amount * checkedRecords.length
      this.form.stocks = checkedRecords
      this.$ajax.post('/wm/stock_process/process', this.form).then(resp => {
        if (resp.code == 0) {
          this.$notify.success('库存锁定成功')
          this.form.submitStatus = 0
          this.form.id = resp.data.id
          this.$ajax.post('/wm/stock_process/submit', this.form).then(resp => {
            if (resp.code == 0) {
              this.$notify.success('库存合并成功')
              this.form.submitStatus = 1
              this.form = global.utils.jsonClone(resp.data)
              this.form.snNew = resp.data.sn
            }
          })
        }
        this.utils.loadHide()
      })
    },

    //撤销提交
    handleUnSubmit() {
      this.form.processType = this.processType
      this.utils.loadShow()
      this.$ajax.post('/wm/stock_process/un_submit', this.form).then(resp => {
        if (resp.code == 0) {
          this.$notify.success('撤销成功')
          this.form.submitStatus = 0
          this.form.snNew = null
          this.checkIds = []
          this.selectChange()
        }
        this.utils.loadHide()
      })
    },

    //打印
    handlePrint() {
      this.$notify.warning('handlePrint未实现')
    },
    //上架
    handleShelf() {
      this.$notify.warning('handleShelf未实现')
    }
  },
  mounted() {
    this.$refs.scan.focus()
  }
}
</script>

<style lang="scss" scoped>
  .page-container{
    /deep/ .van-cell{
      .van-field__label{
        width: 40px;
      }
    }

    .cell-small-box  /deep/ .van-cell{
      padding:5px;
    }
  }

</style>
